// 打印欢迎界面
const { promisify } = require('util')
// 欢迎动画
const figlet = promisify(require('figlet'))
// 清空
const clear = require('clear')
const chalk = require('chalk')
const log = content => console.log(chalk.blue(content))
const { clone } = require('./download')
const open = require('open')

 
const spawn = async(...args) => {

  // 同步 Promise api

  const { spawn } = require('child_process')
  return new Promise(resolve => {
    const proc = spawn(...args)
    // 输出流 子进程 合并到主进程
    proc.stdout.pipe(process.stdout)
    proc.stderr.pipe(process.stderr)
    proc.on('close', () => {
      resolve()
    })
  })
}

const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';

module.exports = async name => {
  // 打开欢迎界面
  clear()
  const data = await figlet.textSync('kkb CLI', {
    font: 'Ghost',
    horizontalLayout: 'default',
    verticalLayout: 'default',
    width: 80,
    whitespaceBreak: true
  })
  log(data)

  // 项目模板
  log('🚀创建项目:' + name)
  await clone('direct:https://github.com/su37josephxia/vue-template.git', name)
  
  // 下载依赖 npm i
  // 子进程中调用
  log('🚀安装依赖....')
  await spawn(command, ['install'], {cwd: `./${name}`})
  log(chalk.green`
    安装完成
  `)
  open('http://localhost:8080')
  await spawn(command, ['run', 'serve'], {cwd: `./${name}`})
}